<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\WeekCheckout;
use Carbon\Carbon;
use GuzzleHttp\Client;
use App\Models\WeekCheckError;
use App\Handlers\WithdrawalHandler;


class WeekCheckoutJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($user, $ttl = 5)
    {
        $this->user = $user;

        // 延时多久后在执行队列
        $this->delay($ttl);
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if (!$this->user->mt_login) {
            return;
        }

        $t1 = (strtotime(getStartOfWeek())) * 1000;
        $t2 = (strtotime(getEndOfWeek(6))) * 1000;

        $week = WeekCheckout::where('user_id', $this->user->id)
            ->whereBetween('created_at', [getStartOfWeek(), getEndOfWeek(6)])->first();

        $checkError = WeekCheckError::where('user_id', $this->user->id)
            ->whereBetween('created_at', [getStartOfWeek(), getEndOfWeek(6)])->first();

        if (!$week) {
            if (!$this->user->mt_login) {
                $url = '?/serverId=4091&accountId=6070001&from='.$t1.'&to='.$t2;
            } else {
                $url = '?serverId=4091&accountId='.$this->user->mt_login.'&from='.$t1.'&to='.$t2;
            }
            $http = new Client([
                'headers' => [
                    'x-api-tenantId' => 'T002612',
                    'x-api-token'    => 'Mk4p43N9gSBAebGr',
                ]
            ]);

            $result = json_decode($http->get($url)->getBody(true)->getContents(), true);

            if ($result['result']) {
                $week = new WeekCheckout();
                $week->admin_user()->associate($this->user);
                $week->profit          = collect($result['data'])->sum('profit') + collect($result['data'])->sum('swap');
                $week->profit_checkout = $week->profit > 0 ? $week->profit * ($this->user->profit_rate / 100) : 0;
                $week->volume          = collect($result['data'])->sum('volume');
                $week->all_data        = json_encode($result);

                $this->user->profit_checkout = $week->profit_checkout;

                if ($week->save()) {
                    WithdrawalHandler::UserBalanceLog($this->user, '周数据汇总');// 记录用户金额变化 周代理结算
                    if ($checkError) {
                        $checkError->status = 1;
                        $checkError->save();
                    }
                }
            } else {
                if (!$checkError) {
                    $checkError = new WeekCheckError();
                    $checkError->admin_user()->associate($this->user);
                    $checkError->save();
                }
                dispatch(new WeekCheckoutJob($this->user, 1000));
            }
        }
    }
}
